<?php

require_once('functions/pageLoad.php');
loginRequired();
$user_session = explode("_", $_SESSION['user']);

if($_SERVER['REQUEST_METHOD'] == 'POST' && strlen($_POST['id']) > 0 && strlen($_POST['reason']) > 0){

// users job?

$sql = "SELECT title FROM jobs WHERE id = '".mysql_real_escape_string($_POST['id'])."' AND user_id = '".$user_session[0]."'";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$rs=mysql_fetch_assoc($query);
$rows = mysql_num_rows($query);

if($rows > 0){

// cancel job

$sql = "UPDATE jobs SET cancellation_reason = '".mysql_real_escape_string($_POST['reason'])."', status = 'Closed' WHERE id = '".mysql_real_escape_string($_POST['id'])."'";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

// cancel quotes

$sql = "UPDATE quotes SET status = 'Cancelled' WHERE job_id = '".mysql_real_escape_string($_POST['id'])."'";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

header("Location: /my-account");

}

}

else{

if(isset($_GET['id'])){

$sql = "SELECT id, reason FROM cancellation_reasons";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

$i = 0;

while($rs=mysql_fetch_assoc($query)){

$checked=($i == 0) ? 'checked="checked"' : '' ;
$reasons.='<input type="radio" name="reason" id="reason_'.$rs['id'].'" value="'.$rs['id'].'"'.$checked.' /> <label for="reason_'.$rs['id'].'" style="font-size: 0.6875em; position: relative; top: -2px;">'.$rs['reason'].'</label><br />';

$i++;

}

$sql = "SELECT title FROM jobs WHERE id = '".mysql_real_escape_string($_GET['id'])."'";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$rs=mysql_fetch_assoc($query);

$content='
<p>Please give your reason for cancelling \''.ucfirst($rs['title']).'\'.</p>
<form method="post" action="/cancel_job.php">
<input type="hidden" name="id" value="'.$_GET['id'].'" />
<br /><br />'.$reasons.'<br />
<input type="image" src="/images/cancel_job.gif" alt="Cancel job" />
</form>
';

}

}

$page_title = 'Cancel job';

include('includes/meta.php');
include('includes/header.php');
include('includes/navigation.php');

?>

<h1><?php echo $page_title; ?></h1>

<?php echo $content; ?>

<?php

include('includes/rightColumn.php');
include('includes/footer.php');

?>